package b649a01.tomasulo;

import java.nio.ByteBuffer;

import b649a01.runners.sim_t;

/***
 * 
 * Class for constructing re-order buffer.
 * 
 * @author Chao Sun
 * @version 1.0
 * 
 */
public class rob {
	private sim_t simulator;
	private int entry;
	private String operator;
	private int step;
	private String dest;
	private Double value;
	private rob_value_pair R[], F[];

	public rob(sim_t s, int e, String op, String d) {
		simulator = s;
		entry = e;
		operator = op;
		step = 1;
		dest = d;
		value = new Double(0.0);
		R = simulator.getR();
		F = simulator.getF();
	}

	public void commit() {
		// write integer into register
		if (operator.equals("ADD") || operator.equals("SUB")
				|| operator.equals("MUL") || operator.equals("DIV")
				|| operator.equals("L") || operator.equals("LI")
				|| operator.equals("MOVE.D")) {
			int index = Integer.parseInt(dest.substring(1));
			if (R[index].getROBEntry() == entry) {
				simulator.setR(index, value, -1);
			} else {
				simulator.setR(index, value, -2);
			}
		}
		// write float pointing into register
		if (operator.equals("ADD.D") || operator.equals("SUB.D")
				|| operator.equals("MUL.D") || operator.equals("DIV.D")
				|| operator.equals("L.D") || operator.equals("MOVE")) {
			int index = Integer.parseInt(dest.substring(1));
			if (F[index].getROBEntry() == entry) {
				simulator.setF(index, value, -1);
			} else {
				simulator.setF(index, value, -2);
			}
		}
		// write integer into memory
		if (operator.equals("S")) {
			int index = Integer.parseInt(dest);
			ByteBuffer buffer = ByteBuffer.allocate(4);
			buffer.putInt(value.intValue());
			byte buf[] = buffer.array();
			for (int i = 0; i < 4; i++) {
				simulator.writeDump(buf[i], index + i);
			}
		}
		// write integer into memory
		if (operator.equals("S.D")) {
			int index = Integer.parseInt(dest);
			ByteBuffer buffer = ByteBuffer.allocate(8);
			buffer.putDouble(value.doubleValue());
			byte buf[] = buffer.array();
			for (int i = 0; i < 8; i++) {
				simulator.writeDump(buf[i], index + i);
			}
		}
	}

	public int getEntry() {
		return entry;
	}

	public String getOperator() {
		return operator;
	}

	public int getStep() {
		return step;
	}

	public void setStep(int i) {
		step = i;
	}

	public String getDest() {
		return dest;
	}

	public void setDest(String s) {
		dest = s;
	}

	public Double getValue() {
		return value;
	}

	public void setValue(Double o) {
		value = o;
	}

}